package com.wjl.picture.post.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjl.picture.common.constant.CommonConstant;
import com.wjl.picture.common.exception.BusinessException;
import com.wjl.picture.common.exception.ErrorCode;
import com.wjl.picture.common.exception.ThrowUtils;
import com.wjl.picture.post.dao.PostDao;
import com.wjl.picture.post.model.dto.PostQueryRequest;
import com.wjl.picture.post.model.entity.Post;
import com.wjl.picture.post.model.vo.PostVO;
import com.wjl.picture.post.service.PostService;
import com.wjl.picture.user.model.entity.User;
import com.wjl.picture.user.model.enums.UserRoleEnum;
import com.wjl.picture.user.model.vo.UserVO;
import com.wjl.picture.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 帖子服务实现
 */
@Service
@Slf4j
public class PostServiceImpl extends ServiceImpl<PostDao, Post> implements PostService {
    @Resource
    private UserService userService;

    @Resource
    private PostDao postDao;


    @Override
    public void validPost(Post post, boolean add) {
        if (post == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = post.getTitle();
        String content = post.getContent();
        String tags = post.getTags();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }


    @Override
    public LambdaQueryWrapper<Post> getLambdaQueryWrapper(PostQueryRequest postQueryRequest) {
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Post> lambdaQueryWrapper = postQueryWrapper.lambda();
        if (postQueryRequest == null) {
            return lambdaQueryWrapper;
        }
        String searchText = postQueryRequest.getSearchText();
        String sortField = postQueryRequest.getSortField();
        String sortOrder = postQueryRequest.getSortOrder();
        Long id = postQueryRequest.getId();
        String title = postQueryRequest.getTitle();
        String content = postQueryRequest.getContent();
        List<String> tagList = postQueryRequest.getTags();
        Long userId = postQueryRequest.getUserId();
        Long notId = postQueryRequest.getNotId();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            lambdaQueryWrapper.like(Post::getTitle, searchText).or().like(Post::getContent, searchText);
        }
        lambdaQueryWrapper.like(StringUtils.isNotBlank(title), Post::getTitle, title);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(content), Post::getContent, content);
        if (CollectionUtils.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                lambdaQueryWrapper.like(Post::getTags, "\"" + tag + "\"");
            }
        }
        lambdaQueryWrapper.ne(ObjectUtils.isNotEmpty(notId), Post::getId, notId);
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(id), Post::getId, id);
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(userId), Post::getUserId, userId);
        lambdaQueryWrapper.eq(Post::getIsDelete, false);
        // 默认按创建时间降序排序
        if (StringUtils.isNotBlank(sortField)) {
        } else {
            lambdaQueryWrapper.orderBy(true, CommonConstant.SORT_ORDER_ASC.equals(sortOrder), Post::getCreateTime);
        }
        return lambdaQueryWrapper;
    }


    @Override
    public PostVO getPostVO(Post post) {
        PostVO postVO = PostVO.objToVo(post);
        // 1. 关联查询用户信息
        Long userId = post.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        postVO.setUser(userVO);
        return postVO;
    }

    @Override
    public Page<PostVO> getPostVOPage(Page<Post> postPage) {
        List<Post> postList = postPage.getRecords();
        Page<PostVO> postVOPage = new Page<>(postPage.getCurrent(), postPage.getSize(), postPage.getTotal());
        if (CollectionUtils.isEmpty(postList)) {
            return postVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = postList.stream().map(Post::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<PostVO> postVOList = postList.stream().map(post -> {
            PostVO postVO = PostVO.objToVo(post);
            Long userId = post.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            postVO.setUser(userService.getUserVO(user));
            return postVO;
        }).collect(Collectors.toList());
        postVOPage.setRecords(postVOList);
        return postVOPage;
    }

    @Override
    public Page<PostVO> listPostVOByPage(PostQueryRequest postQueryRequest) {
        long current = postQueryRequest.getCurrent();
        long pageSize = postQueryRequest.getPageSize();
        Page<Post> postPage = this.page(new Page<>(current, pageSize),
                this.getLambdaQueryWrapper(postQueryRequest));
        return this.getPostVOPage(postPage);
    }

    @Override
    public void validDelete(List<Long> ids, User user) {
        List<Post> list = new LambdaQueryChainWrapper<>(postDao)
                .in(CollUtil.isNotEmpty(ids), Post::getId, ids)
                .select(Post::getId, Post::getUserId)
                .list();
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = list.stream().allMatch(post -> post.getUserId().equals(user.getId()));
        if (!b && !UserRoleEnum.ROLE_ADMIN.getValue().equals(user.getUserRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }
}




